﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Collections;


/// <summary>
/// YCDeal 的摘要说明
/// </summary>
public class YCDeal
{
    //属性
    public string YCId;
    public string Title;
    public string Content;
    public string UserName;
    public int DEPID;
    public string CurrentOperater;
    public DateTime AddDate;
    public string Result;
    public string Status;
    public string Files;
    public DateTime StepAddDate;
    public DateTime StepEndDate;
	public YCDeal()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}
    /// <summary>
    /// 添加异常
    /// </summary>
    /// <returns></returns>
    public Boolean AddYC()
    {
        Boolean success=false;
        try
        {
            
            this.YCId =CreateYCID(this.AddDate.Year.ToString(), this.AddDate.Month.ToString(), "YC");
            string tableName = "YCMS" + this.AddDate.Year.ToString();
            BasicClass BC = new BasicClass();
            this.DEPID = Convert.ToInt32(BC.GetDepIDByUserName(this.UserName));
            string sqlString = "insert into " + tableName + " (YCID,TITLE,CONTENT,DEPID,USERNAME,CURRENTOPERATER,ADDDATE,STATUS) values ('";
            sqlString += this.YCId + "','" + this.Title + "','" + this.Content + "'," + this.DEPID.ToString() + ",'" + this.UserName + "','" + this.CurrentOperater + "','" + this.AddDate.ToString() + "','"+this.Status+"')";
            DBOperation DBO = new DBOperation();
            if (DBO.ExcuteSql(sqlString))
            {
                //CreateFlow();
                //将附件信息写入数据库
                AddAnnexFiles();
                //添加异常步骤第一步，异常提交。
                AddYCSteps();
                //向下一审核人发送信息
                if (this.Status == "0")
                {
                    SendMessageToNextUser();
                }
                success= true;
            }
            else
            {
                success= false;
            }       
               
            
        }
        catch (Exception ex)
        {
            throw (ex); 
            
        }
        return success;
 
    }
    /// <summary>
    /// 将附件信息写入数据库
    /// </summary>
    /// <returns></returns>
    public Boolean AddAnnexFiles()
    {
        Boolean success = false;
        string tableName = "YCFILES" + AddDate.Year.ToString();
        string[] FilePaths = new string[20];
        char[] separator ={ ',' };
        FilePaths = this.Files.Split(separator);
        try
        {
            for (int i = 0; i < FilePaths.Length; i++)
            {
                if (FilePaths[i] != "")
                {
                    string insertSqlString = "insert " + tableName + " (YCID,FILENAME) values ('" + this.YCId + "','" + FilePaths[i].ToString() + "')";
                    DBOperation DBO = new DBOperation();
                    DBO.ExcuteSql(insertSqlString);
                }
            }
            success = true;
        }
        catch (Exception ex)
        {
            string exMsg=ex.Message.ToString();
            success = false;
        }
        return success; 
    }
    /// <summary>
    /// 添加异常步骤的第一步，异常提交
    /// </summary>
    /// <returns>添加成功则返回true，否则返回FALSE</returns>
    public Boolean AddYCSteps()
    {
        //取得要写入数据的异常步骤表明
        string tableName="YCSTEPS"+this.AddDate.Year.ToString();
        Boolean success = false;
        BasicClass BC=new BasicClass ();
        //根据提交者用户名获得该用户所在部门ID
        string DepId=BC.GetDepIDByUserName(this.UserName);
        this.StepAddDate = this.AddDate;
        this.StepEndDate = this.AddDate;
        //构造SQL语句
        string insertSqlString = "insert into " + tableName + " (YCID,SEQ,OPERATORID,TOUSERNAME,ANNOTATE,STATUS,BEGINDATE,ENDDATE,DEPID) values ('";
        insertSqlString += this.YCId + "',1,'" + this.UserName + "','" + this.CurrentOperater + "','异常提交',1,'"+this.StepAddDate.ToString()+"','"+this.StepEndDate.ToString()+"'," + DepId + ")";
        //添加记录
        DBOperation DBO = new DBOperation();
        try
        {
            DBO.ExcuteSql(insertSqlString);
            success = true;
        }
        catch (Exception ex)
        {
            string exMsg = ex.Message.ToString();
            success = false;
        }
        return success;
    }
    public Boolean SendMessageToNextUser()
    {
        Boolean success = false;
        try
        {
            messages sendMsg = new messages();
            sendMsg.Title = "您有新的线损异常需要处理！";
            sendMsg.Content = this.UserName + ",您好！您有新的线损异常需要处理！流程名称：" + this.Title + ".";
            sendMsg.FromUserName = this.UserName;
            sendMsg.ToUserName = this.CurrentOperater;
            sendMsg.TrueFlowID = this.YCId;
            sendMsg.SendCheckDataMessage();
            success = true;
        }
        catch(Exception ex)
        {
            string exMsg = ex.Message.ToString();
            success = false; 
        }
        return success;

    }
    /// <summary>
    /// 生成异常编号ID
    /// </summary>
    /// <param name="strYear">异常添加的年份</param>
    /// <param name="strMonth">异常添加的月份</param>
    /// <param name="DataType">异常编号前缀字符（两位）</param>
    /// <returns>返回唯一异常编号，格式：异常前缀（两位）+年月（六位）+流水号（四位）</returns>
    public string CreateYCID(string strYear, string strMonth, string DataType)
    {
        if (strMonth.Length == 1)
        {
            strMonth = "0" + strMonth;
        }
        string prefixString = DataType + strYear + strMonth;
        string tableName = "YCMS" + strYear;
        string LastItemDataID = "0000";
        string DataFlowID = "";
        DBOperation DBO = new DBOperation();
        //判断本月是否保存过异常，若有则取出最后一个添加的异常的异常编号：YCID
        string sQueryString = "select YCID from " + tableName + " where YCID like '" + prefixString + "%' order by AUTOID desc";
        SqlDataReader sdr = DBO.GetDataReader(sQueryString);
        if (sdr.Read())
        {
            LastItemDataID = sdr[0].ToString();
        }
        //取得流水号整数部分
        DataFlowID = LastItemDataID.Substring(LastItemDataID.Length - 4);
        while (DataFlowID.Substring(0, 1).ToString() == "0")
        {
            DataFlowID = DataFlowID.Substring(1);
            if (DataFlowID.Length == 1)
            {
                break;
            }
        }
        //将流水号加1,并将流水号不足四位
        DataFlowID = Convert.ToString(Convert.ToInt32(DataFlowID) + 1);
        int len = DataFlowID.Length;
        if (len < 4)
            for (int j = 0; j <= 4 - len - 1; j++)
            {
                DataFlowID = "0" + DataFlowID;
            }

        string DataID = prefixString + DataFlowID;
        sdr.Close();
        return DataID;
        
    }
    public int GetUpYCDepIDByYCID(string tempYCID)
    {
        string theYear=tempYCID.Substring(2,4);
        string tabName="YCMS"+theYear;
        string sqlString = "select DEPID from " + tabName + " where YCID='" + tempYCID + "'";
        DBOperation DBO = new DBOperation();
        int depID = Convert.ToInt32(DBO.ExcuteScalar(sqlString));
        return depID;
    }
    public string GetCurrentOperator(string tempYCID)
    {
        string theYear = tempYCID.Substring(2, 4);
        string tabName = "YCMS" + theYear;
        string sqlString = "select CURRENTOPERATER from " + tabName + " where YCID='" + tempYCID + "'";
        DBOperation DBO = new DBOperation();
        string crrentOperator = DBO.ExcuteScalar(sqlString).ToString();
        return crrentOperator; 
    }
    public Boolean DelYC(string tempYCID)
    {
        string theYear=tempYCID.Substring(2,4);
        ArrayList arrl = new ArrayList();
        arrl.Add("delete from YCMS"+theYear+" where YCID='"+tempYCID+"'");
        arrl.Add("delete from YCSTEPS" + theYear + " where YCID='" + tempYCID + "'");
        arrl.Add("delete from YCFILES" + theYear + " where YCID='" + tempYCID + "'");
        string sqlString = "select * from YCFILES" + theYear + " where YCID='" + tempYCID + "'";
        DBOperation DBO=new DBOperation();
        if (DBO.ExcuteSqls(arrl))
        {            
            return true;

        }
        else
        {
            return false;
        } 
    }
    public Boolean checkViewRight(string tempYCID, int DepID)
    {
        bool returnBool;
        string theYear = tempYCID.Substring(2, 4);
        string sqlstring = "select count(*) from YCSTEPS" + theYear + " where DEPID=" + DepID.ToString() + " and YCID='" + tempYCID + "'";
        DBOperation DBO = new DBOperation();
        int count=Convert.ToInt32(DBO.ExcuteScalar(sqlstring));
        if (count > 0)
        {
            returnBool= true;
        }
        else
        {
            //sqlstring = "select count(*) from YCSTEPS" + theYear + " as STEPS inner join USERS as USER on STEPS.TOUSERNAME=USER.USERNAME where STEPS.YCID='" + tempYCID + "'";
            //int count2 = Convert.ToInt32(DBO.ExcuteScalar(sqlstring));
            //if (count > 0)
            //{
            //    returnBool = true;
            //}
            //else
            //{
                returnBool = false;
            //}
        }
        return returnBool;

    }
}
